package com.javaweb.controller;

import com.javaweb.entity.Result;
import com.javaweb.entity.Room;
import com.javaweb.service.RoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/room")
public class RoomController {

    @Autowired
    private RoomService roomService;

    @PostMapping
    public Result add(@RequestBody @Validated Room room) {
        log.info("添加房间。房间：{}", room);
        if (roomService.findByRoomName(room.getRoomName()) == null) {
            roomService.add(room);
            log.info("添加成功。房间：{}", room);
            return Result.success();
        } else {
            log.info("添加失败。房间名已存在");
            return Result.error("房间名已存在");
        }
    }

    @GetMapping("/listAll")
    public Result listAll() {
        log.info("显示所有房间信息");
        List<Room> rooms = roomService.listAll();
        return Result.success(rooms);
    }

    @GetMapping("/listMine")
    public Result listMine() {
        log.info("显示当前用户创建的房间的信息");
        List<Room> rooms = roomService.listMine();
        return Result.success(rooms);
    }

    @PutMapping
    public Result update(@RequestBody @Validated Room room) {
        log.info("更新房间信息。房间：{}", room);
        if (room.getId() == null) {
            log.info("更新失败。房间id不能为空");
            return Result.error("房间id不能为空");
        }
        Room oldRoom = roomService.findById(room.getId());
        if (roomService.findByRoomName(room.getRoomName()) == null //不重名
                || oldRoom.getRoomName().equals(room.getRoomName())) { //或者没有更改房间名
            roomService.update(room);
            log.info("更新成功。房间：{}", room);
            return Result.success();
        } else {
            log.info("更新失败。房间名已存在");
            return Result.error("房间名已存在");
        }
    }

    @PatchMapping("/{id}")
    public Result enterRoom(@PathVariable Integer id){
        log.info("进入房间。id：{}", id);

        return Result.success();
    }
}
